import configparser
import os
import json

def load_config(config_file="config.ini"):
    """
    加载配置文件

    Args:
        config_file (str): 配置文件路径

    Returns:
        configparser.ConfigParser: 解析后的配置对象
    """
    config = configparser.ConfigParser()
    # 设置允许转义序列
    config.optionxform = str

    # 如果配置文件存在则读取，否则创建默认配置
    if os.path.exists(config_file):
        # 使用utf-8编码读取配置文件
        config.read(config_file, encoding='utf-8')
    else:
        # 创建默认配置
        config["ports"] = {
            "tcp": "9000",
            "http": "8080",
            "https": "8443",
            "ssh": "2222",
            "telnet": "2323",
            "ftp": "2121"
        }

        config["telnet"] = {
            "banner": "\\r\\n\\r\\nWelcome to Telnet Server\\r\\nLogin authentication\\r\\n\\r\\n",
            "prompt": "Router>",
            "enable_prompt": "Router#",
            "login_prompt": "Username:",
            "password_prompt": "Password:",
            "hostname": "Router",
            "model": "Cisco IOS Router",
            "version": "12.4(25b)",
            "hardware": "CISCO2811",
            "uptime": "3 days, 14 hours, 25 minutes",
            "interfaces": "FastEthernet0/0,FastEthernet0/1,Serial0/0/0"
        }

        config["ssh"] = {
            "banner": "SSH-2.0-OpenSSH_8.2p1 Ubuntu-4ubuntu0.11\\r\\n"
        }

        # 写入配置文件
        with open(config_file, "w", encoding='utf-8') as f:
            config.write(f)

    return config

def get_telnet_config(config):
    """
    获取Telnet配置

    Args:
        config (configparser.ConfigParser): 配置对象

    Returns:
        dict: Telnet配置字典
    """
    if "telnet" not in config:
        return {}

    telnet_config = {}
    telnet_config["banner"] = config["telnet"].get("banner", "").encode().decode('unicode_escape').encode('latin-1')
    telnet_config["prompt"] = config["telnet"].get("prompt", "Router> ").encode()
    telnet_config["enable_prompt"] = config["telnet"].get("enable_prompt", "Router# ").encode()
    telnet_config["login_prompt"] = config["telnet"].get("login_prompt", "Username: ").encode()
    telnet_config["password_prompt"] = config["telnet"].get("password_prompt", "Password: ").encode()

    telnet_config["device_info"] = {
        "hostname": config["telnet"].get("hostname", "Router"),
        "model": config["telnet"].get("model", "Cisco IOS Router"),
        "version": config["telnet"].get("version", "12.4(25b)"),
        "hardware": config["telnet"].get("hardware", "CISCO2811"),
        "uptime": config["telnet"].get("uptime", "3 days, 14 hours, 25 minutes"),
        "interfaces": config["telnet"].get("interfaces", "FastEthernet0/0,FastEthernet0/1,Serial0/0/0").split(",")
    }

    return telnet_config

def get_ssh_config(config):
    """
    获取SSH配置

    Args:
        config (configparser.ConfigParser): 配置对象

    Returns:
        dict: SSH配置字典
    """
    if "ssh" not in config:
        return {}

    ssh_config = {}
    ssh_config["banner"] = config["ssh"].get("banner", "SSH-2.0-OpenSSH_7.9")
    ssh_config["host_key_path"] = config["ssh"].get("host_key_path", None)
    ssh_config["accept_password"] = config["ssh"].getboolean("accept_password", False)
    ssh_config["accept_publickey"] = config["ssh"].getboolean("accept_publickey", False)
    ssh_config["shell_prompt"] = config["ssh"].get("shell_prompt", "[root@server ~]$ ")
    ssh_config["welcome_message"] = config["ssh"].get("welcome_message", "Welcome to Ubuntu 18.04.6 LTS (GNU/Linux 4.15.0-xyz)")

    allowed_credentials_str = config["ssh"].get("allowed_credentials", "{}")
    try:
        ssh_config["allowed_credentials"] = json.loads(allowed_credentials_str)
    except json.JSONDecodeError:
        ssh_config["allowed_credentials"] = {}

    return ssh_config

def get_ports_config(config):
    """
    获取端口配置

    Args:
        config (configparser.ConfigParser): 配置对象

    Returns:
        dict: 端口配置字典，键为协议名，值为端口号
    """
    if "ports" not in config:
        # 默认端口配置
        return {
            "tcp": 9000,
            "http": 8080,
            "https": 8443,
            "ssh": 2222,
            "telnet": 2323,
            "ftp": 2121
        }

    ports_config = {}
    ports_config["tcp"] = config["ports"].getint("tcp", 9000)
    ports_config["http"] = config["ports"].getint("http", 8080)
    ports_config["https"] = config["ports"].getint("https", 8443)
    ports_config["ssh"] = config["ports"].getint("ssh", 2222)
    ports_config["telnet"] = config["ports"].getint("telnet", 2323)
    ports_config["ftp"] = config["ports"].getint("ftp", 2121)

    return ports_config
